package cn.bincker.mycaptcha.basic.impl;

import cn.bincker.mycaptcha.basic.CaptchaBackgroundCutter;
import cn.bincker.mycaptcha.basic.properties.ImageCaptchaProperties;

import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 默认背景裁剪器
 * 如果高宽不足则放大原图
 * 如果有充足空间则随机裁剪
 */
public class DefaultCaptchaBackgroundCutter implements CaptchaBackgroundCutter {
    private final Random random = new Random();
    private final ImageCaptchaProperties properties;

    public DefaultCaptchaBackgroundCutter(ImageCaptchaProperties properties) {
        this.properties = properties;
    }

    @Override
    public BufferedImage cut(BufferedImage image) {
        int width = properties.getWidth();
        int height = properties.getHeight();
        int rawWidth = image.getWidth();
        int rawHeight = image.getHeight();
        int x, y;
        int targetWidth = width;
        int targetHeight = height;
        if(rawWidth > width){
            if(rawHeight > height){
                x = random.nextInt(rawWidth - targetWidth);
                y = random.nextInt(rawHeight - targetHeight);
            }else{
                targetWidth = width * rawHeight / height;
                targetHeight = rawHeight;
                x = random.nextInt(rawWidth - targetWidth);
                y = 0;
            }
        }else{
            if(rawHeight > height){
                targetWidth = rawWidth;
                targetHeight = height * rawWidth / width;
                x = 0;
                y = random.nextInt(rawHeight - targetHeight);
            }else{
                if(width - rawWidth > height - rawHeight){
                    //宽度差得更多，用宽度作为基准进行放大
                    targetWidth = rawWidth;
                    targetHeight = height * rawWidth / width;
                    x = 0;
                    y = rawHeight > targetHeight ? random.nextInt(rawHeight - targetHeight) : 0;
                }else{
                    //高度差的更多，用高度作为基准进行放大
                    targetWidth = width * rawHeight / height;
                    targetHeight = rawHeight;
                    x = rawWidth > targetWidth ? random.nextInt(rawWidth - targetWidth) : 0;
                    y = 0;
                }
            }
        }
        var result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        var graphics = result.getGraphics();
        if(!graphics.drawImage(image, 0, 0, width, height, x, y, x + targetWidth, y + targetHeight, null)){
            throw new RuntimeException("裁剪验证码背景失败: x=" + x + "\ty=" + y + "\twidth=" + targetWidth + "\theight=" + targetHeight);
        }
        return result;
    }
}
